<template>
    <div class="back">
        <div class="item">
            <div class="detail_item">
                <div class="title">基本信息</div>
                <div class="detail_content">
                    <div class="line">
                        <el-avatar :size="55" :src="UserMessage.avatar" @click="change_goal('pic')" class="pic"/>
                        <div class="name">{{UserMessage.userName}}</div>
                        <el-button text @click="change_goal('name')" class="my_button" type="primary">
                            修改
                        </el-button>
                    </div>
                    <div class="line">
                        <div class="left_data" style="margin-left: 70px;">性别:</div>
                        <div class="showGender">{{UserMessage.gender}}</div>
                        <el-button style="margin: 8px 0 0 14px;" text @click="change_goal('gender')" size="small" class="my_button" type="primary">
                            修改
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <div class="item">
            <div class="detail_item">
                <div class="title">个人信息</div>
                <div class="detail_content">
                    <div class="line">
                        <div class="left_data">手机号码</div>
                        <div class="right_data">{{UserMessage.phone}}</div>
                        <el-button text @click="change_goal('phoneNumber')" class="my_button1" type="primary">
                            更改号码
                        </el-button>
                    </div>
                    <div class="line">
                        <div class="left_data">账户密码</div>
                        <div class="right_data">**********</div>
                        <el-button text @click="change_goal('password')" class="my_button1" type="primary">
                            修改密码
                        </el-button>
                    </div>
                    <div class="line">
                        <div class="left_data">邮箱账号</div>
                        <div class="right_data">{{UserMessage.email}}</div>
                        <el-button text @click="change_goal('message')" class="my_button1" type="primary">
                            更改邮箱
                        </el-button>
                    </div>
                </div>
                <div class="killUser" @click="change_goal('killAccount')">注销账号</div>
            </div>

        </div>
    </div>



    <!--弹窗-->
    <!-- Form -->
    <el-dialog v-model="dialogFormVisible" title="信息更改">
        <el-form :model="form">
          <div v-if="goal==='gender'">
            <el-radio-group v-model="form.gender">
              <el-radio label="男" size="large">男</el-radio>
              <el-radio label="女" size="large">女</el-radio>
            </el-radio-group>
          </div>

            <!--电话号码修改-->
            <div v-if="goal == 'phoneNumber'">
                <el-form-item label="输入新手机号" :label-width="formLabelWidth">
                    <el-input class="" autocomplete="off" v-model="form.newPhoneNumber" placeholder="手机号"/>
                </el-form-item>
                <el-form-item label="输入验证码" :label-width="formLabelWidth">
                    <el-input class="phoneNumberShow" v-model="form.confirmCode" autocomplete="off" placeholder="验证码"/>
                    <el-button class="sendCode" type="primary" v-if="controlSendPhoneConfirm===false" @click="sendPhoneConfirm">发送验证码</el-button>
                    <div style="margin-left: 15px" v-if="controlSendPhoneConfirm===true">{{cunt_time}}</div>
                </el-form-item>
            </div>

            <!--密码修改-->
            <div v-if="goal == 'password'">
                <el-form-item label="输入原密码" :label-width="formLabelWidth">
                    <el-input class="PasswardInput" v-model="form.oldPassword" autocomplete="off" placeholder="输入原密码"/>
                </el-form-item>
                <el-form-item label="输入新密码(字符长度不少于8)" :label-width="formLabelWidth">
                    <el-input class="PasswardInput" v-model="form.newPassword" autocomplete="off" placeholder="输入新密码"/>
                </el-form-item>
                <el-form-item label="确认新密码" :label-width="formLabelWidth">
                    <el-input class="PasswardInput" v-model="form.confirmPassword" autocomplete="off" placeholder="确认新密码"/>
                </el-form-item>
            </div>
            <!--头像修改-->
            <div v-if="goal == 'pic'">
                <div>
                    <input type="file" @change="get_img">
                </div>
                <img v-if="img_perform" :src="img_perform" class="title_image" />
                <!--                    </el-upload>-->
            </div>
            <!-- 名字修改 -->
            <div v-if="goal == 'name'">
                <el-form-item label="账号姓名" :label-width="formLabelWidth">
                    <el-input v-model="form.username" autocomplete="off" placeholder="输入新名字"/>
                </el-form-item>
            </div>
            <!--   邮箱修改   -->
            <div v-if="goal == 'message'">
                <el-form-item label="邮箱账号" :label-width="formLabelWidth">
                    <el-input v-model="form.email" autocomplete="off" placeholder="输入新邮箱"/>
                </el-form-item>
                <el-form-item label="输入验证码" :label-width="formLabelWidth">
                    <el-input class="phoneNumberShow" v-model="form.confirmEmail" autocomplete="off" placeholder="验证码"/>
                    <el-button class="sendCode" type="primary" v-if="controlSendEmailConfirm===false" @click="SendEmailConfirmCode">发送验证码</el-button>
                  <div style="margin-left: 15px" v-if="controlSendEmailConfirm===true">{{cunt_time_email}}</div>
                </el-form-item>
            </div>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible= false">取消</el-button>
        <el-button type="primary" @click="submit_change">
          确认
        </el-button>
      </span>
        </template>
    </el-dialog>

    <!--注销账号-->
    <el-dialog v-if="goal==='killAccount'" v-model="centerDialogVisible" title="Warning" width="30%" center>
    <span>
      谨慎！该操作不可逆转，
    </span>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="logoutAccount">
          继续注销
        </el-button>
      </span>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import {reactive, ref, watch} from 'vue'
import {useRoute,useRouter} from "vue-router";
import {ElMessage, ElNotification} from 'element-plus'
import {
  checkOldPasswordService,
  getConfirmCodeService,
  getEmailConfirmCodeService,
  updateEmailService,
  updatePasswordService,
  updatePhoneService,
  updateUserInfo,
  uploadAvatarService,
  userLogoutService
} from "@/api/request.js";
import {useCounterStore} from "@/stores/counter.js"

let store=useCounterStore()
let userId=store.UserMessage.id

let UserMessage = ref({
  avatar: '',
  userName: '',
  gender: '',
  phone: '',
  email: '',
  password:''
})

watch(()=>store.loginStatus,()=>{
  if(store.loginStatus){
    let message=store.UserMessage
    UserMessage.value.avatar=message.avatar
    UserMessage.value.userName=message.userName
    UserMessage.value.gender=message.gender
    UserMessage.value.phone=message.phone
    UserMessage.value.email=message.email
    UserMessage.value.gender=message.gender
  }
},{deep:true,immediate:true})

const route = useRoute()
const centerDialogVisible = ref(false)

// 弹窗
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

// 控制打开哪一个修改框
const goal = ref('')

function change_goal(x) {
  goal.value = x
  if (x === 'killAccount') {
    centerDialogVisible.value = true
  } else {
    dialogFormVisible.value = true
  }
}

const form = reactive({
  username: null,
  email: null,
  confirmEmail: null,
  gender: null,
  newPhoneNumber: null,
  confirmCode:null,
  oldPassword:null,
  newPassword:null,
  confirmPassword:null,
  userAvatarFile:null,
})

async function submit_change() {
  //更新密码
  if (form.oldPassword !== null && form.newPassword !== null && form.confirmPassword !== null){
    if(await UpdatePassword()===false){
      return
    }
  }
  //更新邮箱
  else if(form.email !== null && form.confirmEmail !== null){
    if(await UpdateEmail()===false){
      return
    }
  }
  //更新手机号
  else if(form.newPhoneNumber !== null && form.confirmCode !== null){
    if(await UpdatePhone()===false){
      return
    }
  }
  //更新姓名
  else if(form.username !== null){
    let resopnse=await updateUserInfo({id:userId,userName:form.username})
    if (resopnse !== null && resopnse.code === 0) {
      ElMessage.error(resopnse.msg);
      return
    }
    store.UserMessage.userName=form.username
    UserMessage.value.userName=form.username
  }
  //更新性别
  else if(form.gender !== null){
    let gender=form.gender
    switch (form.gender) {
      case '男':
        gender = "0"
        break;
      case '女':
        gender = "1"
        break;
    }
    let resopnse=await updateUserInfo({id:userId,gender:gender})
    if (resopnse !== null && resopnse.code === 0) {
      ElMessage.error(resopnse.msg);
      return
    }
    store.UserMessage.gender=form.gender
    UserMessage.value.gender=form.gender
  }
  //更新头像
  else if(form.userAvatarFile !== null){
    let url=await uploadAvatarService(form.userAvatarFile)
    let resopnse=await updateUserInfo({id:userId,avatar:url})
    if (resopnse !== null && resopnse.code === 0) {
      ElMessage.error(resopnse.msg);
      return
    }
    store.UserMessage.avatar=url
    UserMessage.value.avatar=url
  }
  else{
    ElNotification({
      title: '错误',
      message: '修改失败，请检查输入内容！',
      duration: 0,
    });
    return
  }
  // 重置表单字段
  form.gender = null;
  form.email = null;
  form.username = null;
  form.confirmEmail = null;
  form.newPhoneNumber = null;
  form.confirmCode = null;
  form.oldPassword = null;
  form.newPassword = null;
  form.confirmPassword = null;
  form.userAvatarFile = null;
  dialogFormVisible.value = false;
}

//更新密码函数
async function UpdatePassword() {
  if (form.newPassword !== form.confirmPassword) {
    ElMessage.error('两次输入的密码不一致！');
    return false;
  }
  if (await checkOldPasswordService(UserMessage.value.phone, form.oldPassword)) {
    if (form.oldPassword === form.newPassword) {
      ElMessage.error('新旧密码不能相同！');
      return false;
    }
    if (form.newPassword.length < 8) {
      ElMessage.error('新密码长度不能小于八位！');
      return false;
    }
    await updatePasswordService(UserMessage.value.phone, form.newPassword)
    return true;
  } else {
    ElMessage.error('原密码错误！');
    return false;
  }
}

//更新邮箱函数
async function UpdateEmail() {
  let resopnse = await updateEmailService(form.email, form.confirmEmail)
  if (resopnse !== null && resopnse.code === 0) {
    ElMessage.error(resopnse.msg);
    return false;
  }
  store.UserMessage.email=form.email
  UserMessage.value.email = form.email
  return true;
}

//更新手机号函数
async function UpdatePhone() {
  let resopnse = await updatePhoneService(UserMessage.value.phone, form.newPhoneNumber, form.confirmCode)
  if (resopnse !== null && resopnse.code === 0) {
    ElMessage.error(resopnse.msg);
    return false;
  }
  store.UserMessage.phone=form.newPhoneNumber
  UserMessage.value.phone = form.newPhoneNumber
  return true;
}

// 查看上传头像
let img_perform = ref("")
async function get_img(event) {
  let files = event.target.files[0];
  if (files) {
    const reader = new FileReader();
    reader.onload = (e) => {
      if (typeof e.target?.result === 'string') {
        img_perform.value = e.target.result;
      }
    };
    reader.readAsDataURL(files);
    form.userAvatarFile=files;
  }
}

//控制发送短信验证码
let controlSendPhoneConfirm = ref(false)
let cunt_time = ref(30)
async function sendPhoneConfirm() {
  if(form.newPhoneNumber === null) {
    ElMessage.error('请填写手机号！');
    return
  }
  controlSendPhoneConfirm.value = true;
  await getConfirmCodeService(form.newPhoneNumber)
  let timer = setInterval(() => {
    cunt_time.value--;
    if (cunt_time.value === 0) {
      clearInterval(timer);
      controlSendPhoneConfirm.value = false;
      cunt_time.value = 30;
    }
  }, 1000);
}

//发送邮箱验证码
let controlSendEmailConfirm = ref(false)
let cunt_time_email = ref(90)
async function SendEmailConfirmCode() {
  if (form.email !== null) {
    let resopnse=await getEmailConfirmCodeService(form.email)
    console.log(resopnse)
    if(resopnse!==null && resopnse.code === 0){
      ElMessage.error(resopnse.msg);
      return;
    }
    controlSendEmailConfirm.value = true;
    let timer = setInterval(() => {
      cunt_time_email.value--;
      if (cunt_time_email.value === 0) {
        clearInterval(timer);
        controlSendEmailConfirm.value = false;
        cunt_time_email.value = 90;
      }
    }, 1000);
  }else {
    ElMessage.error('请填写邮箱！');
    return;
  }
}

let Router=useRouter()
async function logoutAccount() {
  await userLogoutService(UserMessage.value.phone)
  centerDialogVisible.value = false
  store.loginStatus=false
  store.UserMessage={}
  sessionStorage.removeItem('token')
  await Router.push('/')
}


</script>

<style scoped>
    .back{
        position: relative;
        top: 50px;
        width: 1200px;
        margin: auto;
    }
    .item{
        background-color: white;
        border-radius: 14px;
        width: 90%;
        border: 1px solid #eee;
        margin-bottom: 30px;
        box-shadow: 0 0 10px 0 rgba(0,0,0,.04);
    }

    .detail_item{
        margin-left: 25px;
        margin-right: 25px;
        margin-top: 10px;
        margin-bottom: 10px;
    }
    .title{
        color: #000;
        display: inline-block;
        font-size: 16px;
        font-style: normal;
        font-weight: 600;
        line-height: 25px;
        padding-bottom: 10px;
        width: 100%;
        border-bottom: 2px solid rgba(0,0,0,.06);
    }
    .detail_content{
        margin-top: 15px;
    }
    .line{
        display: flex;
    }
    .name{
        position: relative;
        top: 16px;
        font-size: 18px;
        left: 16px;
    }
    .left_data{
        color: #888;
        margin-block-start: 1em;
        margin-block-end: 1em;
        margin-inline-start: 0px;
        margin-inline-end: 0px;
        font-size: 12px;

    }
    .right_data{
        margin: 12px 6px 0 20px;
        color: rgba(0,0,0,.9)!important;
        font-size: 12px;
    }
    .pic:hover{
        cursor: pointer;
    }
    /*弹窗botton样式*/
    .my_button{
        margin-block-start: 1em;
        margin-block-end: 1em;
        margin-inline-start: 0px;
        margin-inline-end: 0px;
        margin-left: 20px;
    }
    .my_button1{
        margin: 4px 6px 0 8px;
        font-size: 12px;
    }
    /*头像样式*/
    .demo-basic {
        text-align: center;
    }
    .demo-basic .sub-title {
        margin-bottom: 10px;
        font-size: 14px;
        color: var(--el-text-color-secondary);
    }
    .demo-basic .demo-basic--circle,
    .demo-basic .demo-basic--square {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .demo-basic .block:not(:last-child) {
        border-right: 1px solid var(--el-border-color);
    }
    .demo-basic .block {
        flex: 1;
    }
    .demo-basic .el-col:not(:last-child) {
        border-right: 1px solid var(--el-border-color);
    }
    .dialog-footer button:first-child {
        margin-right: 10px;
    }
    .PasswardInput{

    }
    .showGender{
        font-size: 12px;
        line-height: 41px;
        margin-left: 16px;
    }
    .phoneNumberShow{
        width: 29%;
    }
    .sendCode{
        color: #7e7ef1;
        background: white;
        border: none;
    }
    .killUser{
        font-size: 13px;
        font-weight: 800;
        color: #f55252;
        margin-top: 7px;
        margin-bottom: 25px;
        cursor: pointer;
    }
.title_image{
    width: 178px;
    height: 178px;
    display: block;
}
</style>